/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved. 
 */
package com.icinfo.cloud.provider.punish.config.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.YesOrNoEnum;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.punish.common.documentoperate.service.IStageDocCommonOperateService;
import com.icinfo.cloud.provider.punish.common.seal.dto.FileSealInfoQueryDto;
import com.icinfo.cloud.provider.punish.common.seal.dto.SealPreviewInfoRequest;
import com.icinfo.cloud.provider.punish.common.seal.model.ConfigOrgRelatedSeal;
import com.icinfo.cloud.provider.punish.common.seal.service.IFileSealProvinceUnifiedService;
import com.icinfo.cloud.provider.punish.common.seal.vo.ConfigOrgRelatedSealVo;
import com.icinfo.cloud.provider.punish.config.mapper.ConfigOrgRelatedSealMapper;
import com.icinfo.cloud.provider.punish.config.service.IConfigOrgRelatedSealService;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.tools.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 描述: 机构印章关联配置表 config_org_related_seal 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年03月02日
 */
@Service
@Slf4j
public class ConfigOrgRelatedSealServiceImpl extends MyBatisServiceSupport implements IConfigOrgRelatedSealService {

    @Resource
    private ConfigOrgRelatedSealMapper configOrgRelatedSealMapper;
    @Resource
    private IStageDocCommonOperateService stageDocCommonOperateService;
    @Resource
    private IFileSealProvinceUnifiedService fileSealProvinceUnifiedService;
    @Resource
    ResourceLoader resourceLoader;

    @Value("${document.url}")
    private String url;
    @Value("${document.api.uploadBase64File}")
    private String uploadBase64File;

    /**
     * 【V1.0.0】描述：根据机构统一社会信用代码查询机构关联印章配置信息
     *
     * @param uniscid 机构编码
     * @return {@link ConfigOrgRelatedSealVo} 机构关联印章配置信息
     * @author xiangyuyu
     * @date 2022-03-02 19:10
     */
    @Override
    public ConfigOrgRelatedSealVo getOrgRelatedSealConfigInfo(String uniscid,String deptCode) {
        log.info("getOrgRelatedSealConfigInfo start... uniscid:{}", uniscid);
        /*ConfigOrgRelatedSealVo vo = new ConfigOrgRelatedSealVo();
        Example example = new Example(ConfigOrgRelatedSeal.class);
        if(StringUtils.isBlank(deptCode)) {
            example.createCriteria().andEqualTo("uniscid", uniscid);
        }else{
            example.createCriteria().andEqualTo("uniscid", uniscid).andEqualTo("deptCode",deptCode);
        }
        List<ConfigOrgRelatedSeal> configOrgRelatedSeals = configOrgRelatedSealMapper.selectByExample(example);
        if (null != configOrgRelatedSeals & configOrgRelatedSeals.size() > 0) {
            ConfigOrgRelatedSeal configOrgRelatedSeal = configOrgRelatedSeals.get(0);
            BeanUtils.copyProperties(configOrgRelatedSeal, vo);
        }*/
        ConfigOrgRelatedSealVo vo = new ConfigOrgRelatedSealVo();
        List<ConfigOrgRelatedSeal> configOrgRelatedSeals=new ArrayList<>();
        ConfigOrgRelatedSeal configOrgRelatedSeal=new ConfigOrgRelatedSeal();
        Example example = new Example(ConfigOrgRelatedSeal.class);
        example.createCriteria().andEqualTo("uniscid",uniscid).andCondition("(dept_code is null or dept_code='') ");
        configOrgRelatedSeals = configOrgRelatedSealMapper.selectByExample(example);
        if (!ObjectUtils.isEmpty(configOrgRelatedSeals)){
            configOrgRelatedSeal = configOrgRelatedSeals.get(Constant.INTEGER_0);
        }/*else{
            throw new BusinessException("单位印章信息配置为空！");
        }*/
        if(StringUtils.isNotBlank(deptCode)) {
            Example deptExample = new Example(ConfigOrgRelatedSeal.class);
            deptExample.createCriteria().andEqualTo("uniscid", uniscid).andEqualTo("deptCode", deptCode);
            List<ConfigOrgRelatedSeal> configOrgRelatedSealDepts = configOrgRelatedSealMapper.selectByExample(deptExample);
            if (!ObjectUtils.isEmpty(configOrgRelatedSealDepts)) {
                configOrgRelatedSeal = configOrgRelatedSealDepts.get(0);
            }
        }
        BeanUtils.copyProperties(configOrgRelatedSeal, vo);
        log.info("getOrgRelatedSealConfigInfo end... vo:{}", vo);
        return vo;
    }

    /**
     * 【V2.0.0】描述：获取印章预览信息
     *
     * @param request {@link SealPreviewInfoRequest}
     * @return {@link String} 印章图片互联网地址
     * @author xiangyuyu
     * @date 2022-05-16 16:16
     */
    @Override
    public String getSealPreviewInfo(SealPreviewInfoRequest request) {
        //获取空白pdf
        File file;
        try {
            //file = ResourceUtils.getFile("classpath:blankPdfBase64.json");
            //org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:blankPdfBase64.json");

            org.springframework.core.io.Resource resource = new ClassPathResource("blankPdfBase64.json");
            InputStream is = resource.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();
            String data = null;
            while((data = br.readLine()) != null) {
                sb.append(data);
            }

            br.close();
            isr.close();
            is.close();

            /*file = resource.getFile();*/
            FileSealInfoQueryDto queryDto = new FileSealInfoQueryDto();
            String base64 = sb.toString();
            queryDto.setFileBase64(base64);
            queryDto.setFileType("pdf");
            queryDto.setFileTransferForm("1");
            queryDto.setFileBase64(queryDto.getFileBase64());
            queryDto.setAddSignTime(false);
            queryDto.setSealCode("");
            queryDto.setKey("签章处");
            queryDto.setSignType(4);
            queryDto.setSealCode("12");
            queryDto.setPosX(9);
            queryDto.setPosY(4);
            queryDto.setSealCode(request.getSealCode());
            queryDto.setIsSealPreview(YesOrNoEnum.YES.getCode());
            //签章
            Map<String, Object> fileAfterSeal = fileSealProvinceUnifiedService.getFileAfterSeal(queryDto);
            Object errorMsg = fileAfterSeal.get("errorMsg");
            if (!ObjectUtil.isEmpty(errorMsg)) {
                log.warn("fileSealService result:{}",errorMsg);
                throw new BusinessException(fileAfterSeal.get("errorMsg").toString());
            }
            //上传签章后的文件到oss
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("fileBytes", fileAfterSeal.get("fileBytes"));
            jsonObject.put("fileType", "pdf");
            jsonObject.put("fileName", "");
            JSONObject parseObject = JSON.parseObject(HttpUtil.post(url + uploadBase64File, jsonObject.toString()));
            String cd = "code";
            int th = 200;
            if (parseObject.getInteger(cd) == th) {
                String url = parseObject.getJSONObject("data").getString("ossUrl");
                log.info("签章后地址：{}", url);
                //更新到印章表
                ConfigOrgRelatedSeal configOrgRelatedSeal=new ConfigOrgRelatedSeal();
                configOrgRelatedSeal.setSealPdfUrl(url);
                Example example=new Example(ConfigOrgRelatedSeal.class);
                example.createCriteria().andEqualTo("sealCode",request.getSealCode());
                configOrgRelatedSealMapper.updateByExampleSelective(configOrgRelatedSeal,example);
                return url;
            } else {
                log.info("warn receive sign file upload oss fail,result:{}", parseObject.toString());
                throw new BusinessException("签章后上传文件失败：" + jsonObject.getString("message"));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            log.error("未找到空白pdf文件 getSealPreviewInfo");
        } catch (Exception e) {
            e.printStackTrace();
            if(e.getMessage().contains("errorCode:5013")){
                throw new BusinessException("获取预览文件失败：" + "印章未授权");
            }else{
                throw new BusinessException("获取预览文件失败：" + "印章过期或已失效");
            }

        }
        return null;
    }


    /**
     * File文件转String
     * @param file
     * @return
     * @throws IOException
     */
    public static String file2String(final File file) throws IOException {
        if (file.exists()) {
            byte[] data = new byte[(int) file.length()];
            boolean result;
            FileInputStream inputStream = null;
            try {
                inputStream = new FileInputStream(file);
                int len = inputStream.read(data);
                result = len == data.length;
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
            }
            if (result) {
                return new String(data);
            }
        }
        return null;
    }
}